<template>
  <div>
    <el-drawer
      title="充值明细"
      :before-close="handleClose"
      :visible.sync="teamRechargeDetailDialog"
      direction="rtl"
      ref="drawer"
      size="60%"
      custom-class="add-drawer"
    >
      <div class="demo-drawer__content">
        <el-form ref="rechargeDetailRef" :inline="true">
          <el-row>
            <el-col :span="18">
              <el-form-item label="充值时间">
                <el-date-picker
                  v-model="dateTimeRange"
                  type="datetimerange"
                  :value-format="'yyyy-MM-dd HH:mm:ss'"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  size="small"
                >
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item>
                <el-button
                  type="primary"
                  icon="el-icon-search"
                  size="mini"
                  @click="getList"
                  >搜索</el-button
                >
                <el-button
                  type="primary"
                  icon="el-icon-refresh"
                  plain
                  size="mini"
                  @click="resetQuery"
                  >重置</el-button
                >
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <el-table stripe :data="rechargeDetailList" v-loading="loading">
          <el-table-column
            type="index"
            label="序号"
            width="50"
            align="left"
          ></el-table-column>
          <el-table-column
            prop="stationName"
            label="油站名称"
            show-overflow-tooltip
            align="left"
          ></el-table-column>
          <el-table-column
            prop="createdTime"
            label="充值时间"
            show-overflow-tooltip
            align="left"
          ></el-table-column>
          <el-table-column
            prop="balance"
            label="账号余额"
            show-overflow-tooltip
            align="left"
          ></el-table-column>
          <el-table-column
            prop="rechargeAmount"
            label="充值金额"
            show-overflow-tooltip
            align="left"
          ></el-table-column>
          <el-table-column
            prop="giftAmount"
            label="赠送金额"
            show-overflow-tooltip
            align="left"
          ></el-table-column>
          <el-table-column
            prop="afterBalance"
            label="充值后账号余额"
            show-overflow-tooltip
            align="left"
          ></el-table-column>

          <el-table-column
            prop="invoiceStatus"
            label="开票状态"
            show-overflow-tooltip
            :formatter="forinvoiceStatus"
            align="left"
          />

          <el-table-column fixed="right" label="操作" width="120" align="left">
            <template slot-scope="scope">
              <el-button @click="billing(scope.row)" type="text" size="small">
                开票
              </el-button>
              <el-button
                @click="recordBilling(scope.row)"
                type="text"
                size="small"
              >
                开票记录
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <pagination
          v-show="total > 0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />

        <div style="width: 100%; text-align: end; margin-top: 30px">
          <el-button @click="handleClose" type="primary" size="small"
            >返回</el-button
          >
        </div>
      </div>
    </el-drawer>
    <!-- 开票 -->
    <el-dialog title="开票" :visible.sync="dialogFormVisible" width="30%">
      <el-form
        :model="form"
        size="mini"
        :rules="rules"
        ref="ruleForm"
        label-width="100px"
      >
        <el-form-item label="可开票金额 :" :label-width="formLabelWidth">
          <span>{{ form.invoiceBalance }}</span
          ><span> 元</span>
        </el-form-item>
        <el-form-item
          label="开票金额 :"
          :label-width="formLabelWidth"
          prop="invoiceAmount"
        >
          <el-input
            maxlength="12"
            style="width: 150px"
            v-model="form.invoiceAmount"
            autocomplete="off"
          ></el-input>
          <span> 元</span>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="resetForm('ruleForm')" size="mini">取 消</el-button>
        <el-button
          type="primary"
          @click="submitForm('ruleForm')"
          size="mini"
          :disabled="kpdisabled"
          >确 定</el-button
        >
      </div>
    </el-dialog>
    <!-- 开票记录 -->
    <InvoiceRecord
      :invoiceDialog.sync="invoiceDialog"
      :currentRowData="currentRowData"
    ></InvoiceRecord>
  </div>
</template>
<script>
import InvoiceRecord from "./invoice_record.vue";
import {
  getFleetCardRechargeListApi,
  goToInvoice,
} from "@/api/teamCard/teamCardList";
export default {
  name: "TeamRechargeDetail",
  components: { InvoiceRecord },
  props: {
    teamRechargeDetailDialog: {
      type: Boolean,
      default: false,
    },
    currentData: {
      type: Object,
      default: () => {},
    },
  },
  data() {
    let validatePass = (rule, value, callback) => {
      if (value <= 0) {
        return callback(new Error("开票金额不能小于等于0"));
      }
      let amount = Number(String(value).trim());
      const reg = /^\d+(\.\d{1,2})?$/;
      if (!value) return callback(new Error("请输入金额"));
      if (String(value).startsWith("."))
        return callback(new Error("请输入有效数值"));
      if (Number.isNaN(amount)) return callback(new Error("请输入合法数字"));
      if (!reg.test(amount)) return callback(new Error("金额最多保留两位小数"));
      callback();
    };
    return {
      // kpdisabled
      kpdisabled: false,
      // 开票
      form: {
        invoiceBalance: null,
        invoiceAmount: null,
        id: null,
      },
      formLabelWidth: "120px",
      dialogFormVisible: false,

      invoiceDialog: false, // 开票记录弹框
      currentRowData: {}, // 当前选中行数据

      rechargeDetailList: [],
      dateTimeRange: [],
      total: 0,
      loading: false,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
      },
      rules: {
        invoiceAmount: [{ validator: validatePass, trigger: "change" }],
      },
    };
  },
  watch: {
    teamRechargeDetailDialog(val) {
      if (val) {
        this.getList();
      }
    },
  },

  methods: {
    submitForm(ruleForm) {
      this.$refs[ruleForm].validate((valid) => {
        if (valid) {
          this.setGoToInvoice();
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },

    resetForm(ruleForm) {
      this.$refs[ruleForm].resetFields();
      this.dialogFormVisible = false;
    },

    // 确认开票
    setGoToInvoice() {
      this.kpdisabled = true;
      const data = {
        invoiceAmount: this.form.invoiceAmount, //开具发票的金额
        orderNo: this.form.id, //传车队卡充值订单的id
        businessName: "fleet_card_recharge_record", //车队卡开具发票默认为fleet_card_recharge_record
      };
      goToInvoice(data).then((res) => {
        if (res.retCode == 0) {
          this.$message.success(res.message);
          this.dialogFormVisible = false;
          this.kpdisabled = false;
        } else {
          this.$message.error(res.message);
          this.kpdisabled = false;
        }
      });
    },

    // 开票
    billing(row) {
      this.dialogFormVisible = true;
      this.form.id = row.id;
      this.form.invoiceAmount = null;
      this.form.invoiceBalance = row.invoiceBalance;
      this.$nextTick(() => {
        this.$refs["ruleForm"].clearValidate();
        console.log("开票", row);
      });
    },

    // 开票记录
    recordBilling(row) {
      console.log("开票记录", row);
      this.currentRowData = row;
      this.invoiceDialog = true;
    },

    // 开票状态
    forinvoiceStatus(row) {
      let types = {
        0: "未开票",
        1: "已开票",
        2: "部分开票",
        3: "不支持开票",
      };
      return types[row.invoiceStatus];
    },

    resetQuery() {
      this.dateTimeRange = [];
      this.getList();
    },
    handleClose() {
      this.dateTimeRange = [];
      this.$emit("update:teamRechargeDetailDialog", false);
    },
    // 获取充值明细列表
    getList() {
      this.loading = true;
      let id =
        this.currentData && this.currentData.id ? this.currentData.id : "";
      const params = {
        ...this.queryParams,
        fleetCardId: id,
      };
      if (this.dateTimeRange && this.dateTimeRange.length) {
        params.beginTime = this.dateTimeRange[0];
        params.endTime = this.dateTimeRange[1];
      }

      getFleetCardRechargeListApi(params).then((res) => {
        this.rechargeDetailList = res.rows;
        this.total = res.total;
        this.loading = false;
      });
    },
  },
};
</script>
<style scoped lang="scss">
::v-deep .el-drawer {
  .el-drawer__header {
    padding: 20px;
    border-bottom: 1px solid #ddd;
    font-size: 20px;
    margin-bottom: 0px;
  }
  .el-drawer__body {
    padding: 20px;
    overflow: auto;
  }
  .demo-drawer__footer {
    text-align: right;
  }
}
</style>
